package com.fun.feifun.modules.business.controller;
import cn.dev33.satoken.annotation.SaCheckLogin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fun.feifun.base.utils.ControlUtils;
import com.fun.feifun.modules.business.model.*;
import com.fun.feifun.modules.business.model.dto.BusinessPlaceOrderDto;
import com.fun.feifun.modules.business.model.param.BusinessPlaceOrderParam;
import com.fun.feifun.modules.business.model.param.*;
import com.fun.feifun.modules.business.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fun.feifun.base.result.Result;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;

import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author wkf
 * @since 2024-06-04
 */
@RestController
@Api(value = "/business/business-order", tags = "业务订单")
@Slf4j
@SaCheckLogin()
@RequestMapping("/business/business-order")
public class BusinessOrderController {

    @Autowired
    private IBusinessOrderService service;
    @Autowired
    private IBusinessUserService  businessUserService;
    @Autowired
    private IBusinessGoodsService businessGoodsService;

    /**
     * 获取分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "获取分页信息")
    public Result<Page<BusinessOrder>> page(@RequestBody BusinessOrderPage param){
        QueryWrapper<BusinessOrder>  wrapper=new QueryWrapper<>();
        if(ControlUtils.isNotEmpty(param.getRechargeAccount())){
            wrapper.lambda().like(BusinessOrder::getRechargeAccount,param.getRechargeAccount());
        }
        if(ControlUtils.isNotEmpty(param.getCode())){
            wrapper.lambda().eq(BusinessOrder::getCode,param.getCode());
        }
        if(param.getGoodsOperators()!=null){
            wrapper.lambda().eq(BusinessOrder::getGoodsOperators,param.getGoodsOperators());
        }
        if(ControlUtils.isNotEmpty(param.getGoodsCode())){
            wrapper.lambda().eq(BusinessOrder::getGoodsCode,param.getGoodsCode());
        }
        if (ControlUtils.isNotEmpty(param.getGoodsName())){
            wrapper.lambda().like(BusinessOrder::getGoodsName,param.getGoodsName());
        }
        if(ControlUtils.isNotEmpty(param.getBusinessUserCode())){
            wrapper.lambda().eq(BusinessOrder::getBusinessUserCode,param.getBusinessUserCode());
        }
        if(ControlUtils.isNotEmpty(param.getBusinessUserNike())){
            wrapper.lambda().like(BusinessOrder::getBusinessUserNike,param.getBusinessUserNike());
        }
        if(ControlUtils.isNotEmpty(param.getSupplierCode())){
            wrapper.lambda().eq(BusinessOrder::getSupplierCode,param.getSupplierCode());
        }
        if(ControlUtils.isNotEmpty(param.getSupplierName())){
            wrapper.lambda().like(BusinessOrder::getSupplierName,param.getSupplierName());
        }
        if(ControlUtils.isNotEmpty(param.getRemake())){
            wrapper.lambda().like(BusinessOrder::getRemake,param.getRemake());
        }
        if(param.getPayState()!=null){
            wrapper.lambda().eq(BusinessOrder::getPayState,param.getPayState());
        }
        if(param.getState()!=null){
            wrapper.lambda().eq(BusinessOrder::getState,param.getState());
        }
        if(ControlUtils.isNotEmpty(param.getCreateTimeRange())){
            wrapper.lambda().between(BusinessOrder::getCreateTime,param.getCreateTimeRange().get(0),param.getCreateTimeRange().get(1));
        }
        if(ControlUtils.isNotEmpty(param.getReturnTimeRange())){
            wrapper.lambda().between(BusinessOrder::getReturnTime,param.getReturnTimeRange().get(0),param.getReturnTimeRange().get(1));
        }
//        if(ControlUtils.isNotEmpty(param.getStartCreateTime())&&ControlUtils.isNotEmpty(param.getEndCreateTime())){
//            wrapper.lambda().between(BusinessOrder::getCreateTime,param.getStartCreateTime(),param.getEndCreateTime());
//        }
//        if(ControlUtils.isNotEmpty(param.getStartReturnTime())&&ControlUtils.isNotEmpty(param.getEndReturnTime())){
//            wrapper.lambda().between(BusinessOrder::getReturnTime,param.getStartReturnTime(),param.getEndReturnTime());
//        }
        //排序
        if(ControlUtils.isNotEmpty(param.getSort())){
            String sotrKey = ControlUtils.convertToUnderscore(param.getSort());
            if(param.isASC()){
                wrapper.orderByAsc(sotrKey);
            }else{
                wrapper.orderByDesc(sotrKey);
            }
        }
        Page page = new Page(param.getPage(), param.getSize());
        service.page(page,wrapper);
        return Result.success(page);
    }


    /**
     * 根据ID查找数据
     */
    @GetMapping("/findById")
    @ApiOperation(value = "查找")
    public Result findById(@RequestParam("id") Long id){
        BusinessOrder item = service.getById(id);
        if(item==null){
            return Result.err("尚未查询到此ID");
        }
        return Result.success(item);
    }



    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "导入订单表格（未实现）")
    public Result importExcel(@RequestBody List<BusinessOrder> list){
        if(service.saveBatch(list)){
            return Result.success("数据添加成功！");
        }
        return Result.err("数据添加成功！");
    }


    /**
     * 添加数据
     */
    @PostMapping(value = "/placeOrder")
    @ApiOperation(value = "手动创建订单")
    public Result add(@RequestBody BusinessPlaceOrderDto item){
        String pattern = "^1[3456789]\\d{9}$";
        boolean matches = Pattern.matches(pattern, item.getRechargeAccount());
        if(!matches){
            throw new RuntimeException("充值号码，校验不同过请检查是否是手机号");
        }
        QueryWrapper<BusinessUser> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(BusinessUser::getCode,item.getBusinessUserCode());
        BusinessUser user = businessUserService.getOne(wrapper);
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("代理用户不存在");
        }
        if(!ControlUtils.isNotEmpty(user.getSecretKey())){
            throw new RuntimeException("代理用户未生成密匙");
        }
        if(!user.getSecretKey().equals(item.getSecretKey())){
            throw new RuntimeException("代理用户的密匙不一致");
        }
        QueryWrapper<BusinessGoods> goodsWrapper=new QueryWrapper<>();
        goodsWrapper.lambda().eq(BusinessGoods::getCode,item.getGoodsCode());
        BusinessGoods goods = businessGoodsService.getOne(goodsWrapper);
        if(ObjectUtils.isEmpty(goods)){
            throw new RuntimeException("商品不存在");
        }
        if(item.getPrice()!=goods.getAmount().intValue()){
            throw new RuntimeException("商品价格与充值价格不一致");
        }
//        BusinessOrder order = service.placeOrder(goods, user, item);
//        if(order!=null){
//            return Result.success("下单成功！");
//        }
        return Result.err("下单失败！");
    }



    @PostMapping(value = "/payment")
    @ApiOperation(value = "订单-请求支付")
    public Result payment(@RequestParam("orderId") Long orderId) {
        BusinessOrder order= service.getById(orderId);
        service.payment(order,false);
        return Result.err("订单下单支付成功请等待支付完成！");
    }



    @PostMapping("/operationUser")
    @ApiOperation(value = "操作手动成功/手动失败")
    public Result operationGoods(@RequestBody BusinessOrderOperation param){
        service.orderOperate(param);
        return Result.success("操作成功");
    }


    @PostMapping("/summaryPage")
    @ApiOperation(value = "订单汇总")
    public Result<Page<BusinessOrderSummary>> summaryPage(@RequestBody BusinessSummaryPage param){
        return Result.success(service.summaryPage(param));
    }



}

